import React from "react";
import { Link, useLocation } from "react-router-dom";
import { ConfigProvider, App } from "antd";
import zhCN from "antd/locale/zh_CN";
import { useTheme } from "../contexts/ThemeContext";
import { useAuth } from "../contexts/AuthContext";
import TopNavbar from "./TopNavbar";

interface MenuItem {
  path: string;
  icon: string;
  title: string;
  badge?: boolean;
  requireAuth?: boolean;
}

interface LayoutProps {
  children: React.ReactNode;
}

const Layout: React.FC<LayoutProps> = ({ children }) => {
  const location = useLocation();
  const { theme } = useTheme();
  const { isAuthenticated } = useAuth();

  // 主菜单项配置
  const mainMenuItems: MenuItem[] = [
    { path: "/", icon: "i-mdi-home", title: "工作台" },
    { path: "/messages", icon: "i-mdi-message", title: "消息", badge: true },
    { path: "/calendar", icon: "i-mdi-calendar", title: "日程" },
    { path: "/stocks", icon: "i-mdi-database", title: "数据管理" },
  ];

  // 底部菜单项配置
  const bottomMenuItems: MenuItem[] = [
    {
      path: "/profile",
      icon: "i-mdi-account",
      title: "我的",
      requireAuth: true,
    },
    { path: "/settings", icon: "i-mdi-cog", title: "设置" },
  ];

  // 渲染菜单项的函数
  const renderMenuItem = (item: MenuItem) => {
    const isActive = location.pathname === item.path;

    // 如果需要认证但用户未登录，则不显示
    if (item.requireAuth && !isAuthenticated) {
      return null;
    }

    return (
      <Link
        key={item.path}
        to={item.path}
        className={`h-10 flex items-center transition-all duration-200 relative ${
          isActive
            ? "ml-[12px] pl-[12px] text-gray-700 absolute right-0"
            : "mx-auto justify-center text-white/80 hover:text-white hover:shadow-md rounded-lg backdrop-blur-sm border border-white/20 w-10"
        }`}
        style={{
          backgroundColor: isActive ? "white" : "rgba(255, 255, 255, 0.2)",
          borderRadius: isActive ? "8px 0 0 8px" : "8px",
          width: isActive ? "56px" : "40px",
        }}
        title={item.title}
      >
        <i
          className={`${item.icon} text-xl`}
          style={{
            color: isActive ? theme.colors.primary[500] : "currentcolor",
          }}
        ></i>

        {/* 消息徽章 */}
        {item.badge && (
          <span
            className={`absolute -top-1 w-3 h-3 bg-red-500 rounded-full text-xs border ${
              isActive ? "-right-1 border-white" : "-right-1 border-white/30"
            }`}
          ></span>
        )}

        {/* 选中状态的圆角切口 - 延迟显示 */}
        {isActive && (
          <>
            <div
              className="absolute top-[-12px] right-0 w-3 h-3 translate-y-[-12px] opacity-0 animate-[fadeIn_0.1s_ease-out_0.2s_forwards]"
              style={{
                background: `radial-gradient(circle at 0 100%, transparent 12px, white 12px)`,
                transform: "rotate(-270deg)",
              }}
            />
            <div
              className="absolute bottom-[-12px] right-0 w-3 h-3 translate-y-[12px] opacity-0 animate-[fadeIn_0.1s_ease-out_0.2s_forwards]"
              style={{
                background: `radial-gradient(circle at 0 0, transparent 12px, white 12px)`,
                transform: "rotate(270deg)",
              }}
            />
          </>
        )}
      </Link>
    );
  };

  // 不需要布局的页面
  const noLayoutPages = ["/login", "/register", "/404", "/403"];
  const shouldShowLayout = !noLayoutPages.includes(location.pathname);

  if (!shouldShowLayout) {
    return (
      <ConfigProvider
        locale={zhCN}
        theme={{
          token: {
            colorPrimary: theme.colors.primary[500],
            colorSuccess: theme.colors.success,
            colorWarning: theme.colors.warning,
            colorError: theme.colors.error,
            colorInfo: theme.colors.info,
          },
        }}
      >
        {children}
      </ConfigProvider>
    );
  }

  return (
    <ConfigProvider
      locale={zhCN}
      theme={{
        token: {
          colorPrimary: theme.colors.primary[500],
          colorSuccess: theme.colors.success,
          colorWarning: theme.colors.warning,
          colorError: theme.colors.error,
          colorInfo: theme.colors.info,
        },
      }}
    >
      <App>
        <div className="flex h-screen bg-gray-100 dark:bg-gray-900">
          {/* 左侧窄菜单 */}
          <aside
            className="w-16 flex flex-col shadow-lg"
            style={{
              backgroundColor: theme.colors.primary[500],
            }}
          >
            {/* 上部分：常用功能 */}
            <div className="flex-1 py-4">
              <div className="flex flex-col space-y-4 relative">
                {/* Logo */}
                <div
                  className="mx-auto w-10 h-10 rounded-lg flex items-center justify-center mb-4 backdrop-blur-sm border border-white/20"
                  style={{ backgroundColor: "rgba(255, 255, 255, 0.2)" }}
                >
                  <i className="i-mdi-view-dashboard text-white text-xl"></i>
                </div>

                {/* 主菜单项 */}
                {mainMenuItems.map(renderMenuItem)}
              </div>
            </div>

            {/* 下部分：我的和设置 */}
            <div className="py-4 border-t border-white/20">
              <div className="flex flex-col items-center space-y-4 relative">
                {/* 底部菜单项 */}
                {bottomMenuItems.map(renderMenuItem)}
              </div>
            </div>
          </aside>

          {/* 右侧内容区域 */}
          <main className="flex-1 flex flex-col bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 relative">
            {/* 炫丽的背景装饰 */}
            <div className="absolute inset-0 overflow-hidden pointer-events-none">
              <div className="absolute -top-40 -right-40 w-80 h-80 bg-gradient-to-br from-blue-400/20 to-purple-600/20 rounded-full blur-3xl"></div>
              <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-gradient-to-tr from-pink-400/20 to-orange-600/20 rounded-full blur-3xl"></div>
            </div>

            {/* 顶部导航栏 */}
            <div className="relative z-10">
              <TopNavbar />
            </div>

            {/* 内容容器 */}
            <div className="flex-1 overflow-auto relative z-10">{children}</div>
          </main>
        </div>
      </App>
    </ConfigProvider>
  );
};

export default Layout;
